package i18n

import (
	"encoding/json"
	"fmt"
	"os"
)

type LangMap map[string]map[string]string

var translations LangMap

// LoadLangFile 加载语言包
func LoadLangFile(path string) error {
	file, err := os.Open(path)
	if err != nil {
		return fmt.Errorf("failed to open language file: %w", err)
	}
	defer file.Close()

	decoder := json.NewDecoder(file)
	if err := decoder.Decode(&translations); err != nil {
		return fmt.Errorf("failed to decode language JSON: %w", err)
	}
	return nil
}

// T 获取翻译
func T(key, lang string) string {
	if val, ok := translations[key]; ok {
		if langVal, exists := val[lang]; exists {
			return langVal
		}
		// fallback: 返回中文或 key 本身
		if defaultVal, exists := val["cn"]; exists {
			return defaultVal
		}
	}
	return key
}
